package com.bieyang.anjia.ui.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.tsz.afinal.FinalBitmap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.webrtc.mqttclientsample.LogUtis;
import org.webrtc.mqttclientsample.Message;
import org.webrtc.mqttclientsample.MessageService;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Device;
import com.bieyang.anjia.module.Deviceinfo;
import com.bieyang.anjia.module.LoginTypeEnum;
import com.bieyang.anjia.module.NewsInfo;
import com.bieyang.anjia.module.User;
import com.bieyang.anjia.net.NetManager;

import com.bieyang.anjia.sqlitedatabase.AnjiaSQLiteOpenHelper;
import com.bieyang.anjia.sqlitedatabase.SqliteOperation;
import com.bieyang.anjia.ui.adapter.DeviceAdapter;
import com.bieyang.anjia.ui.widget.MyAdGallery;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.ShowProgress;
import com.bieyang.anjia.utils.SubUtils;

import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingActivity;
import com.umeng.analytics.MobclickAgent;

import de.greenrobot.event.EventBus;

/**
 * 滑动主界面
 * */
public class AcMain extends SlidingActivity {

	// menu按钮，点击按钮展示左侧布局，再点击一次隐藏左侧布局
	private Button menuButton;
	private LinearLayout llZixun;
	private RelativeLayout llAddDev;

	ListView lvDevice;
	static Activity activity;
	private Context con;
	TextView tvDeviceManage, tvAlarm, tvFileManage, tvSetting, tvShare,
			tvGrade, tvHelp, loginInfo, tvFankui, tvAbout, tvNewone, tvNewtwo,
			tvTimeOne, tvTimeTwo, tvZixun, tvHead;
	Button btnAnXin;
	private MyAdGallery gallery;
	private int[] imageId = new int[] { R.drawable.img01, R.drawable.img02,
			R.drawable.img03 };
	LinearLayout ovalLayout;
	RelativeLayout rlHead, newsOne, newsTwo, newsMore, newsThree;
	private String[] mris;// 从网络下载图片 ,如果为空加载本地

	/* Gridview */
	int[] resIds = new int[] { R.drawable.device_offline,
			R.drawable.device_online, R.drawable.device_add };
	String[] nameDev = new String[] { "体验（未登录）", "忠机", "添加" };

	Deviceinfo devInfo;
	public List<Deviceinfo> deviceList = new ArrayList<Deviceinfo>();

	String fromLogin;
	DeviceAdapter adapter;

	private ShowProgress progressDialog;

	String code;
	SlidingMenu sm;
	OnClick onClick;

	Date dateOne, dateTwo;

	MyServiceConnection conn;
	List<NewsInfo> newsList;
	String newsTitleOne, newsTitleTwo, newsTimeOne, newsTimeTwo, newsUrlOne,
			newsUrlTwo;

	ImageView guidOne, guidTwo, imgAbout, imgMenu;
	Intent intentNews;

	// 上一次按下back键时间
	private long exitMillis;
	boolean getDev;
	// String[] strShare;
	ImageView imgAnXin; // newNews 新消息红点

	// version upgrade
	String newVersion;
	boolean isFinish = false;
	private int index = 0;
	private ProgressBar progressBar;
	public Dialog dialog, proDialog;
	String rVersion, lVersion;
	protected static final int UPDATA = 0;
	protected static final int REFRESH_LISTVIEW = 10009;

	// = {
	// "http://img.my.csdn.net/uploads/201312/14/1386989803_3335.PNG",
	// "http://img.my.csdn.net/uploads/201312/14/1386989613_6900.jpg",
	// "http://img.my.csdn.net/uploads/201312/14/1386989802_7236.PNG".
	// };//从网络下载图片

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {			
			case REFRESH_LISTVIEW:
				adapter = new DeviceAdapter(con, deviceList);		
				lvDevice.setAdapter(adapter);
				break;
			case UPDATA:
				progressBar.setProgress(index);
				if (index >= 99) {
					proDialog.dismiss();
				}
				SharedPrefsUtil.putValue(App.mContext, "newVersion", 0);
				break;

			case Constants.GET_DEVICE_SUCESS:
				refreshDeviceList();
				break;
			case Constants.ADD_DEVICE_SUCESS:
//				Show.toast(con, "add device ok");
				// initData();
				refreshDeviceList();
				break;
			case Constants.ADD_DEVICE_FAIL:
				Show.toast(con, "add device fail");
				break;

			case Constants.GET_NEWS_SUCESS:
				refreshNews();
				break;
			case Constants.LOGIN_SUCESS:
				if (null != progressDialog)
					progressDialog.dismiss();
				App.isLogin = true;
				refreshView();

				getDevice();

				if (!PubService.isrun) {
					PubService.isrun = true;
					Intent it = new Intent(con, PubService.class); // 开启服务
					startService(it);

					/*
					 * register call
					 */
					conn = new MyServiceConnection();
					Intent serviceIntent = new Intent(con, MessageService.class);
					bindService(serviceIntent, conn, BIND_AUTO_CREATE);
					registerEvent();
					MessageService.startService(con, SubUtils.getUuid(con));
				}

				break;
			case Constants.GET_BANNER_SUCCESS:
				if (null != msg.obj) {
					try {
						JSONArray arr = (JSONArray) msg.obj;
						if (arr.length() > 0) {
							mris = new String[arr.length()];
							AcFindNewsDetail.urlList.clear();
							for (int i = 0; i < arr.length(); i++) {
								JSONObject json = arr.getJSONObject(i);
								mris[i] = json.getString("picture");
								AcFindNewsDetail.urlList.add(json
										.getString("url"));
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				gallery.start(con, mris, imageId, 3000, ovalLayout,
						R.drawable.change_dot_checked,
						R.drawable.change_dot_unchecked);
				
				
//				if (null != msg.obj) {
//					try {
//						JSONArray arr = (JSONArray) msg.obj;
//						mris = new String[arr.length()];
//						AcFindNewsDetail.urlList.clear();
//						for (int i = 0; i < arr.length(); i++) {
//							JSONObject json = arr.getJSONObject(i);
//							mris[i] = json.getString("url");
//							AcFindNewsDetail.urlList.add(json
//									.getString("picture"));
//						}
//					} catch (Exception e) {
//
//					}
//				}
//				gallery.start(con, mris, imageId, 3000, ovalLayout,
//						R.drawable.change_dot_checked,
//						R.drawable.change_dot_unchecked);
				break;
			case Constants.GET_BANNER_FAIL:
				break;
			case Constants.GET_SHARED_STATEMENTS_SUCCESS:
				if (null != msg.obj) {
					ShareSDK.initSDK(con);
					OnekeyShare oks = new OnekeyShare();
					oks.disableSSOWhenAuthorize();
					// 分享时Notification的图标和文字
					oks.setNotification(R.drawable.icon,
							getString(R.string.app_name));
					// text是分享文本，所有平台都需要这个字段
					// if (App.shareIndex < strShare.length) {
					// oks.setText(strShare[App.shareIndex++]);
					oks.setText(msg.obj.toString());
					Log.e("msg", msg.obj.toString());
					// } else {
					App.shareIndex = 0;
					// }
					oks.show(con);
					oks.setAddress("");
				}
				break;
			default:
				if (null != progressDialog)
					progressDialog.dismiss();
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.activity_main);
		activity = this;
		con = AcMain.this;
		App.mContext = getApplicationContext();

		setContentView(R.layout.slide_main);
		// set the behind view
		setBehindContentView(R.layout.slide_left);

		sm = getSlidingMenu();
		sm.setShadowWidth(50);
		// sm.setShadowDrawable(R.drawable.shadow);
		// WindowManager
		// wm=(WindowManager)getSystemService(Context.WINDOW_SERVICE);
		// int with=wm.getDefaultDisplay().getWidth();
		// sm.setBehindOffset(wm.getDefaultDisplay().getWidth()/2);//显示一半的宽度
		sm.setBehindOffset(120); // 设置SlidingMenu打开后，右边留下的宽度
		sm.setFadeDegree(0.35f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

		FinalBitmap.create(this);
		gallery = (MyAdGallery) findViewById(R.id.adgallery);
		ovalLayout = (LinearLayout) findViewById(R.id.ovalLayout);
		// dot_focused;dot_normal
		App.netManager.getBanner(handler, "1");
		gallery.start(con, mris, imageId, 3000, ovalLayout,
				R.drawable.change_dot_checked, R.drawable.change_dot_unchecked);
		gallery.setMyOnItemClickListener(new com.bieyang.anjia.ui.widget.MyAdGallery.MyOnItemClickListener() {
			public void onItemClick(int curIndex) {
				
				intentNews = new Intent(con, AcFindNewsDetail.class);
				intentNews.putExtra("intentNews", curIndex);
				startActivity(intentNews);
			}
		});

		menuButton = (Button) findViewById(R.id.menu_btn);
		lvDevice = (ListView) findViewById(R.id.lvDevice);
		// 仅使用于下拉刷新的列表
		// lvDevice.setOnRefreshListener(new OnRefreshListener() {
		// @Override
		// public void onRefresh() {
		// // TODO Auto-generated method stub
		// new GetDataTask().execute();
		// }
		//
		// });

		menuButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (sm != null) {
					sm.showMenu();
				}
			}
		});

		initView();
		initData();

		registerBoradcastReceiver();
	}

	/**
	 * 1.判断如果是无打扰提示更新，左上菜单按钮红点提示
	 */
	void initData() {
		Log.d("newVersion",
				"" + SharedPrefsUtil.getIntValue(App.mContext, "newVersion", 0));
		switch (SharedPrefsUtil.getIntValue(App.mContext, "newVersion", 0)) {
		case 1:
			imgMenu.setVisibility(View.VISIBLE);
			imgAbout.setVisibility(View.VISIBLE);
			break;
		case 2:
			popUpVersion(2);
			break;
		case 3:
			popUpVersion(3);
			break;

		default:
			break;
		}
	}

	void initView() {
		guidOne = (ImageView) findViewById(R.id.guidOne);
		guidTwo = (ImageView) findViewById(R.id.guidTwo);

		if (0 == SharedPrefsUtil.getIntValue(con, "imgGuid", 0)) {
			guidOne.setVisibility(View.VISIBLE);
			guidTwo.setVisibility(View.VISIBLE);
		} else if (1 == SharedPrefsUtil.getIntValue(con, "imgGuid", 0)) {
			guidOne.setVisibility(View.VISIBLE);
		}

		guidOne.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent arg1) {
				// TODO Auto-generated method stub
				v.setVisibility(View.GONE);
				SharedPrefsUtil.putValue(con, "imgGuid", 2);
				return true;
			}
		});
		guidTwo.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent arg1) {
				// TODO Auto-generated method stub
				v.setVisibility(View.GONE);
				SharedPrefsUtil.putValue(con, "imgGuid", 1);
				return true;
			}
		});

		onClick = new OnClick();
		newsOne = (RelativeLayout) findViewById(R.id.newsOne);
		newsOne.setOnClickListener(onClick);

		newsTwo = (RelativeLayout) findViewById(R.id.newsTwo);
		newsTwo.setOnClickListener(onClick);

		newsThree = (RelativeLayout) findViewById(R.id.newsThree);
		newsThree.setOnClickListener(onClick);

		llZixun = (LinearLayout) findViewById(R.id.llZixun);
		llZixun.setOnClickListener(onClick);

		newsMore = (RelativeLayout) findViewById(R.id.newsMore);
		newsMore.setOnClickListener(onClick);

		tvNewone = (TextView) findViewById(R.id.tvNewone);
		tvNewtwo = (TextView) findViewById(R.id.tvNewtwo);
		tvTimeOne = (TextView) findViewById(R.id.tvTimeOne);
		tvTimeTwo = (TextView) findViewById(R.id.tvTimeTwo);

		llAddDev = (RelativeLayout) findViewById(R.id.llAddDev);
		llAddDev.setOnClickListener(onClick);

		btnAnXin = (Button) findViewById(R.id.btnAnXin);
		btnAnXin.setOnClickListener(onClick);

		// lvDevice.setOnItemClickListener(new OnItemClick());
		/* left */

		loginInfo = (TextView) findViewById(R.id.tvHead);// loginInfo,tvHead
		// rlHead = (RelativeLayout) findViewById(R.id.rlHead);
		loginInfo.setOnClickListener(onClick);

		tvZixun = (TextView) findViewById(R.id.tvZixun);
		tvZixun.setOnClickListener(onClick);
		tvHelp = (TextView) findViewById(R.id.tvHelp);
		tvHelp.setOnClickListener(onClick);

		tvFankui = (TextView) findViewById(R.id.tvFankui);
		tvFankui.setOnClickListener(onClick);

		tvFileManage = (TextView) findViewById(R.id.tvFileManage);
		tvFileManage.setOnClickListener(onClick);

		tvShare = (TextView) findViewById(R.id.tvShare);
		tvShare.setOnClickListener(onClick);

		tvGrade = (TextView) findViewById(R.id.tvGrade);
		tvGrade.setOnClickListener(onClick);

		tvAbout = (TextView) findViewById(R.id.tvAbout);
		tvAbout.setOnClickListener(onClick);

		imgAbout = (ImageView) findViewById(R.id.imgAbout);
		imgMenu = (ImageView) findViewById(R.id.imgMenu);
		imgAnXin = (ImageView) findViewById(R.id.imgAnXin);

		if (App.isLogin) {
			loginInfo.setText(SharedPrefsUtil.getStringValue(App.mContext,
					"phone", ""));
		} else {
			loginInfo.setText(R.string.noLogin);
		}

		if (null == progressDialog) {
			progressDialog = new ShowProgress(con);
			progressDialog.setMessage(R.string.loadingText);
		}

		/*
		 * register call
		 */
		// conn = new MyServiceConnection();
		// Intent serviceIntent = new Intent(this, MessageService.class);
		// bindService(serviceIntent, conn, BIND_AUTO_CREATE);
		//
		// registerEvent();
		// MessageService.startService(con, SubUtils.getUuid(con));

		// 获取资讯
		// App.netManager.getNewsMore(con, handler);

		adapter = new DeviceAdapter(con, deviceList);
		lvDevice.setAdapter(adapter);
		if (App.isFirstGetDev) {
			App.isFirstGetDev = false;
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						while (true) {
							Thread.sleep(5 * 1000);
							handler.post(new Runnable() {
								@Override
								public void run() {
									if (App.isLogin) {
										getDevice();
									}
								}
							});

						}
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
		}
	}

	void refreshView() {
		if (App.isLogin) {
			loginInfo.setText(SharedPrefsUtil.getStringValue(App.mContext,
					"phone", ""));
		} else {
			loginInfo.setText(R.string.noLogin);
		}
	}

	void refreshDeviceList() {
		deviceList.clear();
		if (App.isLogin == false || null == deviceList
				|| 0 == NetManager.deviceList.size()) {
			llAddDev.setVisibility(View.VISIBLE);
		} else {
			llAddDev.setVisibility(View.GONE);
			deviceList.addAll(NetManager.deviceList);
			System.out.println("deviceListSize=" + deviceList.size());
		}
		for(int i=0;i<deviceList.size();i++){
			Log.d("status:"+deviceList.get(i).name,  deviceList.get(i).online);
		}
		handler.sendEmptyMessage(REFRESH_LISTVIEW);
		
//		adapter = new DeviceAdapter(con, deviceList);		
//		lvDevice.setAdapter(adapter);
//		adapter.notifyDataSetChanged();		 
		
	}

	@SuppressLint("SimpleDateFormat")
	void refreshNews() {
		SqliteOperation sqlOperation = new SqliteOperation(con,
				AnjiaSQLiteOpenHelper.dbName, AnjiaSQLiteOpenHelper.version);
		newsList = sqlOperation.queryNews("isdelete=?", new String[] { "F" },
				null);
		Log.d("newsList", "" + newsList.size());
		if (newsList.size() >= 2) {
			newsTitleOne = newsList.get(newsList.size() - 1).title;
			newsTimeOne = newsList.get(newsList.size() - 1).submitTime;
			newsUrlOne = newsList.get(newsList.size() - 1).webUrl;
			tvNewone.setText(newsTitleOne);
			tvTimeOne.setText(newsTimeOne);

			newsTitleTwo = newsList.get(newsList.size() - 2).title;
			newsTimeTwo = newsList.get(newsList.size() - 2).submitTime;
			newsUrlTwo = newsList.get(newsList.size() - 2).webUrl;
			tvNewtwo.setText(newsTitleTwo);
			tvTimeTwo.setText(newsTimeTwo);

		} else if (newsList.size() == 1) {
			newsTitleOne = newsList.get(newsList.size() - 1).title;
			newsTimeOne = newsList.get(newsList.size() - 1).submitTime;
			newsUrlOne = newsList.get(newsList.size() - 1).webUrl;
			tvNewone.setText(newsTitleOne);
			tvTimeOne.setText(newsTimeOne);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		imgAnXin.setVisibility(App.newNews ? View.VISIBLE : View.GONE);

		if (!getDev) {
			getDevice();
		}
		// Log.d("onResume", "onResume" + "login:" +
		// String.valueOf(App.isLogin));

		if (App.isLogin) {
			loginInfo.setText(SharedPrefsUtil.getStringValue(App.mContext,
					"phone", ""));
		} else {
			login();
		}

		refreshDeviceList();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getDev = false;

		if (null != conn)
			unbindService(conn);
		EventBus.getDefault().unregister(this);
		MobclickAgent.onKillProcess(this);

		unregisterReceiver(mBroadcastReceiver);

		LogUtis.log("Video destory..........");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long exitMillis = System.currentTimeMillis();
			if (exitMillis - this.exitMillis < 5000) {
				finish();
			} else {
				Show.toast(con, getString(R.string.main_press_again));
			}
			this.exitMillis = exitMillis;
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	class OnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent;
			switch (v.getId()) {
			case R.id.tvZixun:
				startActivityAnim(new Intent(con, AcFindNews.class));

				break;
			case R.id.llAddDev:
				intent = new Intent(con, AcHelpDetail.class);
				intent.putExtra("fromAcMain", "fromAcMain");
				startActivity(intent);
				break;

			case R.id.btnAnXin:
				if (App.isLogin) {
					startActivityAnim(new Intent(con, AcAnXin.class));
				} else {
					Show.toast(con, R.string.please_login);
				}
				break;

			/* left */

			case R.id.tvHead: // rlHead
				if (App.isLogin) {
					Log.d("isLogin", "isLogin");
					startActivityAnim(new Intent(con, AcMyInfo.class));
				} else {
					Log.d("noLogin", "noLogin");
					startActivityAnim(new Intent(con, AcLogin.class));
				}
				break;

			case R.id.tvHelp:
				startActivityAnim(new Intent(con, AcHelp.class));

				break;
			case R.id.tvFankui:
				startActivityAnim(new Intent(con, AcFankui.class));
				break;

			case R.id.tvShare:
				// strShare =
				// getResources().getStringArray(R.array.share_content);
				App.netManager.getShareStatements(handler);
				// ShareSDK.initSDK(con);
				// OnekeyShare oks = new OnekeyShare();
				// oks.disableSSOWhenAuthorize();
				// 分享时Notification的图标和文字
				// oks.setNotification(R.drawable.icon,
				// getString(R.string.app_name));
				// text是分享文本，所有平台都需要这个字段
				// if (App.shareIndex < strShare.length) {
				// oks.setText(strShare[App.shareIndex++]);
				// } else {
				// App.shareIndex = 0;
				// }

				// oks.show(v.getContext());
				// oks.setAddress("");
				// startActivityAnim(new Intent(con, WXEntryActivity.class));
				break;
			case R.id.tvGrade:
				Uri uri = Uri.parse("market://details?id=" + getPackageName());
				intent = new Intent(Intent.ACTION_VIEW, uri);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				break;
			case R.id.tvAbout:
				startActivityAnim(new Intent(con, AcAbout.class));
				break;

			default:
				break;
			}

		}

	}

	public class OnItemClick implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position,
				long arg3) {
			Intent intent;
			if (App.isLogin) {
				if (deviceList.size() == position || 0 == deviceList.size()) {
					// Show.toast(con, R.string.tip_add_device,
					// Toast.LENGTH_LONG);
					intent = new Intent(con, AcHelpDetail.class);
					intent.putExtra("fromAcMain", "fromAcMain");
					startActivity(intent);

				} else {
					intent = new Intent(con, AlarmSetActivity.class);
					intent.putExtra("id", deviceList.get(position).id);
					intent.putExtra("uuid", deviceList.get(position).uuid);
					intent.putExtra("name", deviceList.get(position).name);
					startActivity(intent);
				}

			} else {
				startActivity(new Intent(con, AcTiYan.class)); // tiyan
			}

		}
	}

	private void registerEvent() {
		EventBus.getDefault().register(this, "onMessage", Message.class);
	}

	private class MyServiceConnection implements
			android.content.ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

	}

	public void onMessage(final Message message) {
		LogUtis.log("from:" + message.getFrom() + "," + "to:" + message.getTo()
				+ "," + "content:" + message.getContent() + "," + "type:"
				+ message.getType());
		switch (message.getType()) {

		case PHONE:

			break;

		default:
			break;
		}
	}

	public void getDevice() {

		getDev = true;
		Device divice = new Device();
		divice.setMemberId(SharedPrefsUtil.getStringValue(App.mContext,
				"memberId", ""));

		App.netManager.getDev(con, divice, handler);
	}

	public void startActivityAnim(Intent intent) {
		startActivity(intent);
		overridePendingTransition(R.anim.base_slide_right_in,
				R.anim.base_slide_remain);

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(0, R.anim.base_slide_right_out);
	}

	/**
	 * 
	 * 处理二维码扫描过来的uuid,添加设备
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (110 == requestCode && 112 == resultCode) {
			code = data.getStringExtra("code");
			Log.d("code", "coade:" + code);
			if (code != null && !("".equals(code))) {
				String phone = SharedPrefsUtil.getStringValue(App.mContext,
						"phone", "");
				Log.d("code", code + ";phone:" + phone);
				App.netManager.addDevice(code, phone, handler);
			}
		} else if (123 == requestCode) {
			refreshDeviceList();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public static Activity getCurrentActivity() {
		return activity;
	}

	/**
	 * exit when login other
	 * 
	 * */
	public void registerBoradcastReceiver() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.LOGIN_OTHER);
		myIntentFilter.addAction(Constants.NEW_NEWS);
		// 注册广播
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Constants.LOGIN_OTHER)) {
				loginInfo.setText(R.string.noLogin);
				if (!App.isLogin) {
					NetManager.deviceList.clear();
					// refreshDeviceList();
					startActivity(new Intent(con, AcLogin.class));
					finish();
				}

			} else if (action.equals(Constants.NEW_NEWS)) {
				imgAnXin.setVisibility(App.newNews ? View.VISIBLE : View.GONE);
			}
		}

	};

	void login() {

		String uuid = SubUtils.getUuid(con);
		User user = new User();
		user.setCardNo(SharedPrefsUtil
				.getStringValue(App.mContext, "phone", ""));
		user.setPassword(SharedPrefsUtil.getStringValue(App.mContext,
				"password", ""));
		user.setUuid(uuid);
		user.setType(LoginTypeEnum.MAIN);

		progressDialog.show();
		Log.d("mainLogin",
				"mainLogin:"
						+ SharedPrefsUtil.getStringValue(App.mContext, "phone",
								""));
		App.netManager.login(con, user, handler);

	}

	void popUpVersion(final int typeUpgrade) {
		dialog = new Dialog(con);
		LayoutInflater inflater = LayoutInflater.from(con);// 初始化
		View view = inflater.inflate(R.layout.pop_version_upgrade, null);
		TextView tvTitle = (TextView)view.findViewById(R.id.tvTitle);
		tvTitle.setText("v"+App.verinfo.sNewVerNo+"升级内容");
		TextView tvUpContent = (TextView) view.findViewById(R.id.tvUpContent);
		tvUpContent.setText(App.verinfo.sUpMsg);

		// 点确定，开始下载更新
		view.findViewById(R.id.exitBtn0).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						LayoutInflater inflater = LayoutInflater.from(con);
						proDialog = new Dialog(con);
						proDialog.setCancelable(false);
						View popView = inflater.inflate(
								R.layout.pop_progress_layout, null);
						progressBar = (ProgressBar) popView
								.findViewById(R.id.progressBar1);
						progressBar.setMax(100);
						proDialog.getWindow();
						proDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
						proDialog.setContentView(popView);
						downFile(App.verinfo.sUpDownLinkAddr);
					}
				});

		// 点取消 ，弹窗消失
		view.findViewById(R.id.exitBtn1).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (3 == typeUpgrade) {
							finish();
						} else {
							dialog.dismiss();
							SharedPrefsUtil.putValue(App.mContext,
									"newVersion", 1);
						}
					}
				});
		dialog.getWindow();
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(view);
		dialog.show();
	}

	public void downFile(final String url) {
		dialog.dismiss();
		proDialog.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					// long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(
								Environment.getExternalStorageDirectory(),
								App.verinfo.sFileName); // Config.UPDATE_SAVENAME
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;

							index = (int) (count * 100)
									/ (App.verinfo.iFileSize); //
							// fileName
							Log.d("index", String.valueOf(index));
							AcMain.this.progressDialog = progressDialog;
							handler.sendEmptyMessage(UPDATA);

						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	//
	public void down() {
		handler.post(new Runnable() {
			public void run() {
				progressDialog.cancel();
				update();
			}
		});
	}

	// INSTALL APK
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), App.verinfo.sFileName)),
				"application/vnd.android.package-archive"); // Config.UPDATE_SAVENAME
		startActivity(intent);
	}

}
